#!/usr/bin/ruby
require 'rubygems'
require 'mechanize'
require 'date'
require 'net/smtp'
require 'base64'
require 'fanmairenkou'

class Send_mail
	def send(from, from_alias, to, to_alias, subject, message)
		msg = <<END_OF_MESSAGE
From: #{from_alias} <#{from}>
To: #{to_alias}
Subject: #{subject}
Date: #{Time.now}

#{message}
END_OF_MESSAGE

		Net::SMTP.start('mail.fake.cn', 25 ) do |smtp|
			smtp.send_message msg, from, to
			smtp.finish
		end
	end
end

def send_msg(content)
	from = "AutoWaMei@XiaoNei.com"
	from_alias = "AutoWaMei"
	to = ["fake@fake.cn"]
	to_alias = "liubin <fake@fake.cn>"
	subject = "Auto WaMei Report"

	send_mail = Send_mail.new
	send_mail.send(from, from_alias, to, to_alias, subject, content)
end

username = Base64.decode64("emp1bGl1Ymlu")
password = Base64.decode64("mypass_base64")

def parse_ids(page)
	slave_tag = page.parser.search("//ul[@class='helotlist']/li")
	slave_tag.map do |tag|
		entry = {}
		entry[:id] = tag["id"].split("_").last
		name_tag = tag.search("/div/a")[0]
		if(name_tag)
			entry[:name] = name_tag.inner_text
		end
		entry
	end
end

def parse_property_first(page)
	prop = page.parser.search("//div[@class='float-left w260 mt10']/div/div/div/a")
	$bossname = prop[0].inner_text
	$bossid = prop[0]["href"].match(/\?i=(\d*)/)[1]
	if prop.size == 2 
		puts "[校内网]: 不好了, #{prop[0].inner_text}大老板, 您被#{prop[1].inner_text}这个小人给买走了, 请您赶紧赎身吧!\n"
		content = "#{prop[0].inner_text}大老板, 您好！\n\t由于小的疏忽，让#{prop[1].inner_text}这个无良小人把您买走了, 请您赶紧赎身吧!\n" 
		content += "\n---------------------------\nhttp://friendsell.xiaonei.com/friendsell/home.do\n您忠心耿耿的,自动挖煤机\n#{Time.now()}"
		send_msg( content ) if Time.now().hour >= 22 and Time.now().hour < 23
	end
	# 经济情况
	prop = page.parser.search("//dl[@class='propertylist clearfix']/dd/span")
	puts "[校内网]: 您的经济情况如下：" 
	puts "    身价: #{prop[0].inner_text}"
	puts "    资产: #{prop[1].inner_text}"
	puts "    现金: #{prop[2].inner_text}"
	puts "    奴隶: #{prop[3].inner_text}"
	puts "    工具: 全球仅有的超牛B的无敌挖煤机"
	if prop[3].inner_text.to_i < 12
		puts "[校内]: 报告#{$bossname},奴隶小于12个"
		content = "#{$bossname},bigboss!\n\t大事不妙，奴隶造反，跑了！\n\t不过请你老放心，我追去了。。。\n---------------------\n城管of煤矿\n#{Time.now()}"
		send_msg( content )
		renshe = Renshe.new( $agent, $bossid, 100000, 5000 )
		renshe.parse_people()
		#renshe.list_people()
		renshe.buy_people()
	end
	prop[2].inner_text[/[0-9]*$/].to_i
end

def check_status(page)
	marketevents = page.parser.search("//dl[@class='marketeventlist']")
	out = { :firstid => "", :firsttext => "", :status => "" }
	out[:firstid] = marketevents[0].search("/dd/a[1]")[0]["href"].match(/\?i=(\d*)/)[1]
	#out[:firsttext] = marketevents[0].search("/dd")[0].inner_text.strip.split("\r").join("").split("\n").join("").split("\t").join("")
	out[:firsttext] = marketevents[0].search("/dd")[0].inner_text.gsub(/[\n\r\t]/,"")
	marketevents.each do |e|
		out[:status] += e.search("/dd/a[1]")[0]["href"].match(/\?i=(\d*)/)[1]
	end
	out
end

def parse_property_second(page)
	prop = page.parser.search("//dl[@class='propertylist clearfix']/dd/span")
	prop[2].inner_text[/[0-9]*$/].to_i
end

begin
	$agent = WWW::Mechanize.new
	$agent.user_agent_alias = "Windows IE 6"
	puts "[程序]: <#{Time.now()}> 正在登录校內..."
	page = $agent.get("http://www.xiaonei.com")
	search_form = page.forms.first
	search_form.fields.name("email").value = username
	search_form.fields.name("password").value = password
	$agent.submit(search_form)
	page = $agent.get("http://apps.xiaonei.com/friendsell/home.do")
	puts "[校内网]: 欢迎来到山西最牛X的黑煤窑."
	cash1 = parse_property_first(page)
	oldstatus = check_status(page)

	if ARGV.length == 0
		entries = parse_ids(page)
		puts "[无敌挖煤机]: 此次挖煤任务启动...\n"
		num = 1
		entries.each do |entry|
			puts "********* No. #{num} 号挖煤工 #{entry[:name]} ***********"
			$agent.post("http://friendsell.xiaonei.com/friendsell/usecard.do", \
									{:basetype => "1", :cardid => "19", :toid => entry[:id].to_s, :toid1 => "20202020", :type => "1"})
			$agent.post("http://friendsell.xiaonei.com/friendsell/usecard.do", \
									{:basetype => "1", :cardid => "20", :toid => entry[:id].to_s, :toid1 => "20202020", :type => "1"})
			$agent.post("http://friendsell.xiaonei.com/friendsell/usecard.do", \
									{:basetype => "1", :cardid => "23", :toid => entry[:id].to_s, :toid1 => "20202020", :type => "1"})
			puts "[我]: #{entry[:name]}, 给老子去挖煤!"
			puts "[#{entry[:name]}]: 是, boss!"
			puts "[校内网]: #{entry[:name]}屁颠屁颠地跑去挖煤了."
			page2 = $agent.post("http://friendsell.xiaonei.com/friendsell/abuse.do", {:id => entry[:id].to_s , :paintype => "5" })
			puts "[#{entry[:name]}]: 报告boss, 偶的煤已经挖完了!"
			status = check_status(page2);
			puts "[会计]: #{status[:firsttext]}" if status[:firstid] == entry[:id] and status[:status] != oldstatus[:status]
			oldstatus = status
			puts "[我]: 嗯，好吧，#{entry[:name]}, 赏你根小布丁!"
			$agent.post("http://friendsell.xiaonei.com/friendsell/comfort.do", {:id => entry[:id].to_s , :comforttype=> "2" })
			puts "[#{entry[:name]}]: 谢谢boss! boss大恩大德永生难忘!"
			num += 1
		end
		puts "********************"
	end

	page = $agent.get("http://apps.xiaonei.com/friendsell/home.do")
	cash2 = parse_property_second(page)
	puts "[无敌挖煤机]: 此次挖煤任务结束, 一共赚得#{cash2 - cash1}两银子."
	puts "[校内网]: 山西最牛X的黑煤窑欢迎您下次再来."
	puts "[程序]: <#{Time.now()}> 我要走了, 1个小时后再来哦~~~\n"
rescue Exception => e
	puts "#{e}\n"
end
